import "./utils/wx.applet.extensions.js";
import { user } from "./mock-info.js";
import { merge } from "./utils/index";
import { staticUrl,isDebug } from "./services/config.js";

// 重写console 
console.log = (function(oriLogFunc){
    return function(str){
      if (isDebug){//判断配置文件是否开启日志调试
        oriLogFunc.call(console, str);
      }
    }
  })(console.log);

App({
    _require: file => require("./" + file),
    globalData: {
        Custom: {},
        StatusBar: 0,
        CustomBar: 0,
        ajaxLoaderIndex: 0,
         //全局数据管理
        navBarHeight: 0, // 导航栏高度
        menuBotton: 0, // 胶囊距底部间距（保持底部间距一致）
        menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
        menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
    },
    user: {
        phone: "",
        token: "",
        clearManager:false,
        clearTask:false,
        userInfo: {
            showAlert:true
        },
    },
     
 /**
 * @description 设置导航栏信息
 */
 setNavBarInfo () {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    this.globalData.navBarHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
    this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
    this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    this.globalData.menuHeight = menuButtonInfo.height;
    },
    onLaunch: function () {
        this.setNavBarInfo();
        this.getStorageInfo();
        this.user = merge(true, this.user, user);
        wx.getNetworkType({
            success(res) {
                const networkType = res.networkType;
                if (networkType == "2g") {
                    wx.showToast({
                        title: "当前网络2g,不建议上传图片",
                        icon: "none",
                    });
                }
                if (networkType == "3g") {
                    wx.showToast({
                        title: "当前网络3g,建议单张图片上传",
                        icon: "none",
                    });
                }
            },
        });
        this.initSystemInfo();
        //检测更新
        this.checkProkectSystem();
        this.user.userInfo.showAlert = true;

   


    },
    initSystemInfo(){
        wx.getSystemInfo({
            success: e => {
                this.globalData.StatusBar = e.statusBarHeight;
                let capsule = wx.getMenuButtonBoundingClientRect();
                if (capsule) {
                    this.globalData.Custom = capsule;
                    this.globalData.CustomBar = capsule.bottom + capsule.top - e.statusBarHeight;
                } else {
                    this.globalData.CustomBar = e.statusBarHeight + 50;
                }
            },
        });
    },
    getStorageInfo(){

        const userStorage = wx.getStorageSync("user");
        if (userStorage) {
            this.user = merge(true, this.user, userStorage);
        }
        wx.login({
          timeout: 3000,
          success:res=>{
              let new_user = this.user;
              new_user.wxcode = res.code;
             this.user = new_user;
             console.log(this.user);
             console.log(res);

          }
        })
        // console.log(this.user);
    },
    logout(url = "/pages/entrance/index") {
        this.user = {
            phone: "",
            token: "",
            userInfo: {},
        };
        
        wx.clearStorage();

        if (url) {
            wx.reLaunch({
                url: url,
            });
        }
        if (url === "redirect-login") {
            let pageList = getCurrentPages();
            let _page = pageList[pageList.length - 1] || null;
            _page && _page.selectComponent("#pageBox").login();
        }
    },
    login(option) {

        console.log(option.data);
        // console.log(data);
        // cityCode  departmentId  governmentIds(不要s取第一个)  orgCategoryId
        this.user.token = option.data.token || "";
        this.user.phone = option.data.tel || "";
        this.user.clearManager = option.data.clearManager ||false;
        this.user.clearTask = option.data.clearTask ||false;
        // clearTask
        let governmentIds = option.data.governmentIds;
       
        let openId = option.data.openId||"";
        let showAlert = true; //this.user.userInfo.showAlert;
     
        let head_url = ""
        if(option.data.headPortrait){
            head_url = staticUrl + option.data.headPortrait;
        }

        this.user.userInfo = {
            id: option.data.id || "",
            cityCode: option.data.cityCode || "",
            openId:option.data.openId||"",
            name: option.data.name || "",
            username: option.data.username || "",
            position: option.data.position || "",
            departmentName: option.data.departmentName || "",
            headPortrait: head_url,
            cityCode:option.data.cityCode || "",
            departmentId:option.data.departmentId || "",
            governmentId:governmentIds[0],
            orgCategoryId:option.data.orgCategoryId || "",
            
            showAlert:showAlert
        };
        wx.setStorage({
            key: "user",
            data: this.user
        });

  
    },
    loader(state,options){
        // console.log("111")
        // console.log(options);
        // console.log("2222")
        if (state) {
            if (this.globalData.ajaxLoaderIndex === 0) {
                wx.showLoading({
                    title: "加载中",
                    mask: true,
                });
            }
            this.globalData.ajaxLoaderIndex++;
        } else {
        
            this.globalData.ajaxLoaderIndex--;
            if (this.globalData.ajaxLoaderIndex === 0) {
                setTimeout(() => {
                    this.globalData.ajaxLoaderIndex === 0 && wx.hideLoading() && wx.stopPullDownRefresh({
                        success: (res) => {
                          
                        },
                      });
                }, options ==200 ? 0:2000);
            }
        }
    },
    /**
     * 当小程序启动，或从后台进入前台显示，会触发 onShow
     */
    onShow: function (options) {},

    /**
     * 当小程序从前台进入后台，会触发 onHide
     */
    onHide: function () {},

    /**
     * 当小程序发生脚本错误，或者 api 调用失败时，会触发 onError 并带上错误信息
     */
    onError: function (msg) {},
    checkProkectSystem(){
        // console.log("=====检测更新=====")
        let res = wx.getSystemInfoSync();
        console.log("=====检测更新=====",res)
        // console.log(res);
        if (wx.canIUse('getUpdateManager')) {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
              console.log('onCheckForUpdate====', res.hasUpdate)
              // 请求完新版本信息的回调
              if (res.hasUpdate ) {
                console.log('res.hasUpdate====')
                updateManager.onUpdateReady(function () {
                  wx.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    success: function (res) {
                      console.log('success====', res)
                      // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                      if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                      }
                    }
                  })
                })
                updateManager.onUpdateFailed(function () {
                  // 新的版本下载失败
                  wx.showModal({
                    title: '已经有新版本了哟~',
                    content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
                  })
                })
              }
            }),
            updateManager.onUpdateReady(function (e) {
                wx.showModal({
                  title: '更新提示',
                  content: '新版本已经准备好，是否重启应用？',
                  success: function (res) {
                    if (res.confirm) {
                      // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                      updateManager.applyUpdate()
                    }
                  }
                })
              })  
            updateManager.onUpdateFailed(function (e) {
                // 新版本下载失败
                console.log(e);
              })
        }
       
    },
});
